﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace Bamboo.Utils
{
    public class XMLUtils
    {
        public static void DeserializeList<T>(IList<T> objList, string fileName)
        {
            if (File.Exists(fileName) == false)
            {
                objList.Clear();
                return;
            }
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                DeserializeList(objList, fs);
            }
        }

        public static void DeserializeList<T>(IList<T> objList, Stream s)
        {
            objList.Clear();
            XmlSerializer xmls = new XmlSerializer(typeof(List<T>));
            try
            {
                s.Position = 0;
                List<T> tempList = (List<T>)xmls.Deserialize(s);
                foreach (T item in tempList)
                {
                    objList.Add(item);
                }
            }
            catch (Exception ex)
            {
                //do nothing
            }
        }


        public static T DeserializeObject<T>(string fileName)
            where T : class, new()
        {
            if (File.Exists(fileName) == false)
                return default(T);
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                return DeserializeObject<T>(fs);
            }
        }

        public static T DeserializeObject<T>(Stream s)
            where T : class, new()
        {
            try
            {
                s.Position = 0;
                XmlSerializer xmls = new XmlSerializer(typeof(T));
                T obj = (T)xmls.Deserialize(s);
                return obj;
            }
            catch
            {
                return default(T);
            }
        }

        public static void SerializeList<T>(IList<T> objList, string fileName)
        {
            if (objList.Count == 0) return;
            XmlSerializer xmls = new XmlSerializer(typeof(BindingList<T>));
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                xmls.Serialize(fs, objList);
            }
        }

        public static void SerializeObject<T>(T obj, string fileName)
        {
            if (obj == null) return;
            XmlSerializer xmls = new XmlSerializer(typeof(BindingList<T>));
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                xmls.Serialize(fs, obj);
            }
        }
    }

}
